import axios from 'axios'
/**
 *  本地存储
 */
import StorageService from '@/utils/dataStore'
/**
 * 获取当前页面路由
 */
import GetRoute from "@/router/index";
/**
 * 
 */
const instance = axios.create({ timeout: 6000 })

/**
 * 添加请求拦截器
 */
instance.interceptors.request.use(
    (config) => {
        //网络设置
        config.baseURL = 'http://192.168.1.30:29007/'
        //网络设置
        //config.baseURL = 'https://cg.zhipu-china.com/g1/t/gsi/'
        // 获取本地存储数据
        const localDataValue = StorageService.localData.token
        //请求头
        config.headers = {
            ...config.headers,
            'Content-Type': 'application/json',
        }
        //当前路径
        const CurrentPath = GetRoute.currentRoute.value.name
        //判断
        if (localDataValue && CurrentPath !== 'login') {
            //请求头
            config.headers = {
                Authorization: 'Bearer ' + localDataValue, //如果要求携带在请求头中
            }
        }
        return config
    },
    (error) => {
        Promise.reject(error)
    },
)

/**
 * 添加响应拦截器
 */
instance.interceptors.response.use(
    (resp) => {
        if (resp.data.status > 200) {
            return Promise.reject(resp.data?.msg)
        }
        return resp.data
    },
    (err) => {
        if (err.response && err.response.status >= 400) {
            return Promise.reject(
                err.response?.data.msg.length > 15
                    ? `响应状态码${err.response?.status},详情请查看network`
                    : err.response.data.msg,
            )
        }
        return Promise.reject('网络异常!!!')
    },
)

export default instance
